package com.gz.mylife.im;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gz.mylife.R;
import com.gz.mylife.util.FileUtils;
import com.zl.smartmall.library.util.Tools;

public class PhotoUtil implements OnClickListener,OnTouchListener{
	
	private static final int PICTURE_FROM_ALBUM = 38;
	private static final int PICTURE_FROM_CAMERA = 39;
	private static final int CROP_FROM_CAMERA = 40;
	
	private TextView mTextTitle;
	private Button mPictureFromAlbum;
	private Button mPictureFromCamera;
	private Button mCancel;
	private LinearLayout mSelectPictureLayout;
	private LinearLayout mSelectMenuLayout;
	
	private File mPhotoPath;
	private Uri mOutputUri;
	private Config mDefaultConfig;
	private Config mCurrentConfig;
	//private PhotoCallback mCallback;
	
	private Activity mActivity;
	private Context mContext;

	public PhotoUtil(Activity activity) {
		mActivity = activity;
		mContext = activity.getApplicationContext();
		mSelectPictureLayout = (LinearLayout) mActivity.findViewById(R.id.select_pic_ll);
		
		mSelectMenuLayout =(LinearLayout) mSelectPictureLayout.findViewById(R.id.layout_select_menu);
		mTextTitle = (TextView) mSelectPictureLayout.findViewById(R.id.txt_from_title);
		mPictureFromAlbum = (Button) mSelectPictureLayout.findViewById(R.id.btn_pic_from_album);
		mPictureFromCamera = (Button) mSelectPictureLayout.findViewById(R.id.btn_pic_from_camera);
		mCancel = (Button) mSelectPictureLayout.findViewById(R.id.btn_cancel);
		mPictureFromCamera.setOnClickListener(this);
		mPictureFromAlbum.setOnClickListener(this);
		mCancel.setOnClickListener(this);
		mSelectPictureLayout.setOnTouchListener(this);
		
		mDefaultConfig = new Config();
	}
	
	public Config getDefaultConfig(){
		return mDefaultConfig;
	}
	
	public void setTitle(String title){
		if(mTextTitle.getVisibility() == View.GONE)
			mTextTitle.setVisibility(View.GONE);
		mTextTitle.setText(title);
	}
	
	public void hideTitle(){
		if(mTextTitle.getVisibility() == View.VISIBLE)
			mTextTitle.setVisibility(View.GONE);
	}
	
	/**
	 * 设置自定义比例图片，还有callback
	 * @param callback
	 */
	public void takePhoto(Config config){
		if(config == null){
			mCurrentConfig = mDefaultConfig;
		} else {
			mCurrentConfig = config;
		}
		showSelectView();
	}
	
	/**
	 * 1比1的正方形图片
	 * @param callback
	 */
	public void takePhoto(PhotoCallback callback){
		mCurrentConfig = mDefaultConfig;
		if(callback !=null){
			mCurrentConfig.setPhotoCallback(callback);
		}
		showSelectView();
	}
	
	public void takePhoto(){
		PhotoCallback callback = null;
		takePhoto(callback);
	}
	
	private void showSelectView() {
		if (mSelectPictureLayout.getVisibility() == View.GONE) {
			mSelectPictureLayout.setVisibility(View.VISIBLE);
			AnimationSet animationSet = null;
			TranslateAnimation translateAnimation = null;
			animationSet = new AnimationSet(true);
			translateAnimation = new TranslateAnimation(
					Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
					0f, Animation.RELATIVE_TO_SELF, 1f,Animation.RELATIVE_TO_SELF, 0f);
			translateAnimation.setDuration(500);
			animationSet.addAnimation(translateAnimation);
			mSelectMenuLayout.startAnimation(animationSet);
		}
	}
	public boolean isShow(){
		if (mSelectPictureLayout.getVisibility() == View.GONE) {
			return false;
		}
		return true;
	}

	public void hideSelectView() {
		AnimationSet animationSet = null;
		TranslateAnimation translateAnimation = null;
		animationSet = new AnimationSet(true);
		translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
				0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				0f, Animation.RELATIVE_TO_SELF, 1f);
		translateAnimation.setDuration(500);
		animationSet.addAnimation(translateAnimation);
		mSelectMenuLayout.startAnimation(animationSet);
		translateAnimation.setAnimationListener(new AnimationListener(){
			@Override
			public void onAnimationEnd(Animation arg0) {
				mSelectPictureLayout.setVisibility(View.GONE);
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

	private void startPhotoZoom(Uri inUri,Uri outUri) {
		//调用CropImage类对图片进行剪切
		Intent intent = new Intent(mActivity, CropImage.class);
        Bundle extras = new Bundle();
        extras.putInt("aspectX", mCurrentConfig.mCropOption.aspectX);
        extras.putInt("aspectY",  mCurrentConfig.mCropOption.aspectY);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        intent.setDataAndType(inUri, "image/jpeg");
        intent.putExtras(extras);
		mActivity.startActivityForResult(intent, CROP_FROM_CAMERA);
	}
	
//	private void startPhotoZoom(Uri uri) {
//		Intent intent = new Intent("com.android.camera.action.CROP");
//		intent.setDataAndType(uri, "image/*");
//		intent.putExtra("crop", "true");
//		intent.putExtra("aspectX", mCurrentConfig.mCropOption.aspectX); // X方向上的比例
//		intent.putExtra("aspectY", mCurrentConfig.mCropOption.aspectY); // Y方向上的比例
//		intent.putExtra("outputX", mCurrentConfig.mCropOption.outputX); // 裁剪区的宽
//		intent.putExtra("outputY", mCurrentConfig.mCropOption.outputY); // 裁剪区的高
//		intent.putExtra("scale", mCurrentConfig.mIsScale);
//		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//		intent.putExtra("return-data", false);
//		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//		intent.putExtra("noFaceDetection", true); // no face detection
//		mActivity.startActivityForResult(intent, CROP_FROM_CAMERA);
//	}

	// 拍照，成功后还要调用startPhotoZoom 进行裁剪
	private void takePhotoByCamera(Uri output) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra("scale", mCurrentConfig.mIsScale);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		mActivity.startActivityForResult(intent, PICTURE_FROM_CAMERA);
	}

	// 获取相册的图片并裁剪
//	private void takePhotoByAlbum(Uri output) {
//		// Launch picker to choose photo for selected contact
//		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
//		intent.setType("image/*");
//		intent.putExtra("crop", "true"); // 发送裁剪信号
//		intent.putExtra("aspectX", mCurrentConfig.mCropOption.aspectX); // X方向上的比例
//		intent.putExtra("aspectY", mCurrentConfig.mCropOption.aspectY); // Y方向上的比例
//		intent.putExtra("outputX", mCurrentConfig.mCropOption.outputX); // 裁剪区的宽
//		intent.putExtra("outputY", mCurrentConfig.mCropOption.outputY); // 裁剪区的高
//		intent.putExtra("scale", mCurrentConfig.mIsScale); // 是否保留比例
//		intent.putExtra("scaleUpIfNeeded", true);// 去黑边
//		intent.putExtra("return-data", false); // 是否将数据保留在Bitmap中返回
//		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
//		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // 将URI指向相应的file:
//		intent.putExtra("noFaceDetection", true); // // no face detection
//		mActivity.startActivityForResult(intent, PICTURE_FROM_ALBUM);
//	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case CROP_FROM_CAMERA:
			if (resultCode == Activity.RESULT_OK) {
				if (mPhotoPath!= null && mPhotoPath.exists()) {
					if(mCurrentConfig.mIsReturnImage){
						Bitmap bitmap = getFitBitmap(mPhotoPath, mCurrentConfig.mImageSize);
						mCurrentConfig.mCallback.onBack(bitmap, mPhotoPath.getPath());
					} else {
						mCurrentConfig.mCallback.onBack(null, mPhotoPath.getPath());
					}
				} else {
					mPhotoPath = null;
				}
			} else {
				if(mPhotoPath!=null && mPhotoPath.exists()){
					mPhotoPath.delete();
					mPhotoPath = null;
				}
			}
			break;
		case PICTURE_FROM_CAMERA:
			if (resultCode == Activity.RESULT_OK) {
				rotateAndOutput(mCurrentConfig.mImageSize);
				if(mCurrentConfig.mIsCrop){
					startPhotoZoom(mOutputUri,mOutputUri);
				} else{
					mCurrentConfig.mCallback.onBack(null, mPhotoPath.getPath());
				}
			} else {
				if(mPhotoPath!=null && mPhotoPath.exists()){
					mPhotoPath.delete();
					mPhotoPath = null;
				}
			}
			break;

		case PICTURE_FROM_ALBUM:
			if (resultCode == Activity.RESULT_OK) {
				if(!mCurrentConfig.mIsCrop){
					Uri uri = data.getData();
					mPhotoPath = FileUtils.createTempFile(mContext,".png");
					Tools.compressBitmap(mContext, mPhotoPath,uri);
					if (mPhotoPath!= null && mPhotoPath.exists()) {
						if(mCurrentConfig.mIsReturnImage){
							Bitmap bitmap = getFitBitmap(mPhotoPath, mCurrentConfig.mImageSize);
							mCurrentConfig.mCallback.onBack(bitmap, mPhotoPath.getPath());
						} else {
							mCurrentConfig.mCallback.onBack(null, mPhotoPath.getPath());
						}
					} else {
						mPhotoPath = null;
					}
					
				} else {
					Uri uri = data.getData();
					mPhotoPath = FileUtils.createTempFile(mContext,".png");
					startPhotoZoom(uri,Uri.fromFile(mPhotoPath));
				}
				
//				if (mPhotoPath!= null && mPhotoPath.exists()) {
//					if(mCurrentConfig.mIsReturnImage){
//						Bitmap bitmap = getFitBitmap(mPhotoPath, mCurrentConfig.mImageSize);
//						mCurrentConfig.mCallback.onBack(bitmap, mPhotoPath.getPath());
//					} else {
//						mCurrentConfig.mCallback.onBack(null, mPhotoPath.getPath());
//					}
//				} else {
//					mPhotoPath = null;
//				}
			} else {
				if(mPhotoPath!=null && mPhotoPath.exists()){
					mPhotoPath.delete();
					mPhotoPath = null;
				}
			}
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(mSelectPictureLayout.getVisibility() == View.VISIBLE){
				hideSelectView();
				return true;
			}
		} 
		return false;
	}
	

	@Override
	public void onClick(View v) {
		if (mPictureFromCamera == v) {
			mPhotoPath = FileUtils.createTempFile(mContext,".png");
			mOutputUri = Uri.fromFile(mPhotoPath);
			takePhotoByCamera(mOutputUri);
			hideSelectView();
		} else if (mPictureFromAlbum == v) {
			/*
			if(mCurrentConfig.mIsCrop){
				mPhotoPath = FileUtils.createTempFile(mContext,".png");
				mOutputUri = Uri.fromFile(mPhotoPath);
				takePhotoByAlbum(mOutputUri);
			} else {
				Intent pickIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				mActivity.startActivityForResult(pickIntent, PICTURE_FROM_ALBUM);
			}*/
			Intent pickIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			mActivity.startActivityForResult(pickIntent, PICTURE_FROM_ALBUM);
			hideSelectView();
		} else if(mCancel == v){
			hideSelectView();
		}
	}
	
	private void rotateAndOutput(int imageSize){
		if(mPhotoPath == null || !mPhotoPath.exists())
			return;
		Bitmap bitmap = null;
		try {
			// 获取图片旋转角度
			int degree = readPictureDegree(mPhotoPath.getAbsolutePath());
			// 等比缩放图片
			bitmap = getFitBitmap(mPhotoPath,imageSize);
			if(degree > 0){
				// 旋转图片到正常的角度
				bitmap = rotaingImageView(degree, bitmap);
			}
			File outPath = FileUtils.createTempFile(mContext, ".jpg");
			FileOutputStream fos = new FileOutputStream(outPath);
			if (null != fos) {
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
				fos.flush();
				fos.close();
			}
			mPhotoPath.delete();
			mPhotoPath = outPath;
			mOutputUri = Uri.fromFile(mPhotoPath);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
	}

	public static class Config {
		boolean mIsReturnImage = true;
		boolean mIsCrop = true;
		boolean mIsScale = true;
		int mImageSize = 720;
		PhotoCallback mCallback;
		CropOption mCropOption = new CropOption();
		
		public Config setPhotoCallback(PhotoCallback callback){
			mCallback = callback;
			return this;
		}
		
		public Config setIsCrop(boolean isCrop){
			mIsCrop = isCrop;
			return this;
		}
		
		public Config setIsScale(boolean isScale){
			mIsScale = isScale;
			return this;
		}
		
		public Config setIsReturnImage(boolean isReturnImage){
			mIsReturnImage = isReturnImage;
			return this;
		}
		
		public Config setImageSize(int imageSize){
			mImageSize = imageSize;
			return this;
		}
		
		public Config setCropOption(CropOption option){
			mCropOption = option;
			return this;
		}
	}
	
	public static class CropOption {
		int aspectX=1;   // X方向上的比例
		int aspectY=1;   // Y方向上的比例
		int outputX=200; // 裁剪区的宽
		int outputY=200; // 裁剪区的高
		
		public CropOption(){}
		
		public CropOption(int _aspectX,int _aspectY,int _outputX,int _outputY) {
			aspectX = _aspectX;
			aspectY = _aspectY;
			outputX = _outputX;
			outputY = _outputY;
		}
	}
	
	public interface PhotoCallback {
		/**
		 * 如果配置了返回false 则image返回null
		 * @param bitmap
		 * @param path
		 */
		public void onBack(Bitmap bitmap,String path);
	}
	
	private static Bitmap getFitBitmap(File file,int destWidth) {
		if(!file.exists())
			return null;
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), opt);

		opt.inSampleSize =getFitSample(opt.outWidth,opt.outHeight,destWidth,destWidth);
		opt.inPreferredConfig = Bitmap.Config.ARGB_8888; 
		opt.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(file.getPath(), opt);
		return bitmap;
	}
	
	public static int getFitSample(int width, int height, int destWidth, int destHeight){
		int sample = 1;
		while(width>destWidth){
			if(width<destWidth+200){
				break;
			}
			sample = sample*2; 
			width = width/sample;
			height = height/sample;
		}
		
		while(height>destHeight){
			if(height<destHeight+200){
				break;
			}
			sample = sample*2; 
			width = width/sample;
			height = height/sample;
		}
		return sample;
	}
	
	/** 
     * 旋转图片 
     * @param angle 
     * @param bitmap 
     * @return Bitmap 
     */  
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
        //旋转图片 动作  
        Matrix matrix = new Matrix();;  
        matrix.postRotate(angle);  
       // System.out.println("angle2=" + angle);  
        // 创建新的图片  
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
        return resizedBitmap;  
    }
	
	/** 
	 * 读取图片属性：旋转的角度 
	 * @param path 图片绝对路径 
	 * @return degree旋转的角度 
	 */  
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		return true;
	}
}
